package top.lingkang.authoritypro.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import top.lingkang.authoritypro.data.dao.UserDao;
import top.lingkang.authoritypro.data.entity.Menu;
import top.lingkang.authoritypro.data.entity.Role;
import top.lingkang.authoritypro.data.entity.User;
import top.lingkang.authoritypro.data.pojo.RoleAuthority;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lingkang
 * @date 2021/12/14
 */
@Component
public class UserDetailsServiceConfig implements UserDetailsService {
    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //查询用户
        User user = userDao.findByUsername(s);
        if (user == null) {
            throw new UsernameNotFoundException("帐号：" + s + " 不存在！");
        }
        List<RoleAuthority> grantedAuthorities = new ArrayList<>();
        List<Role> roles = userDao.getRole(user);
        List<Menu> menus = new ArrayList<>();
        if (!CollectionUtils.isEmpty(roles)) {
            roles.forEach(r -> {
                RoleAuthority authority = new RoleAuthority();
                authority.setRole(r.getName());
                grantedAuthorities.add(authority);
                menus.addAll(userDao.getMenu(r));
            });
        }

        //spring5+要求密码加密，我这里传明文密码来加密
        String password = new BCryptPasswordEncoder().encode(user.getPassword());
        top.lingkang.authoritypro.data.pojo.UserDetails userDetails = new top.lingkang.authoritypro.data.pojo.UserDetails(user.getUsername(), password, grantedAuthorities);
        userDetails.setUser(user);
        userDetails.setMenus(menus);
        return userDetails;
    }
}
